<!--
 * @Author: quit
 * @Date: 2021-11-23 10:13:56
 * @LastEditTime: 2022-01-15 15:58:09
 * @Descripttion:图片管理
-->
<template>
    <div id="ImageManagement-container">
        <div class="app-container">
            <el-card>
                <!-- 搜索区域 -->
                <el-row class="row1">
                    <el-divider content-position="left">{{ $t('divider.divider1') }}</el-divider>
                    <div class="search">
                        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                            <el-form-item :label="'图片名称'">
                                <el-input v-model="searchForm.appname" :placeholder="'请输入图片名称'" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-zoom-in" @click="getImagesLsit">{{ $t('button.search') }}</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-row>
                <!-- 按钮组 -->
                <el-row>
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItem">{{ '添加图片' }}</el-button>
                    <!-- <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button> -->
                </el-row>
                <!-- 表格 -->
                <el-row>
                    <el-table
                        ref="imgTable"
                        v-loading="loading"
                        :data="tableData"
                        :empty-text="$t('table.emptyText')"
                        style="width: 100%"
                        :max-height="tableHeight"
                    >
                        <!-- <el-table-column type="selection" min-width="40" fixed="left" /> -->
                        <el-table-column prop="imageid" label="ID" min-width="45" fixed="left" />
                        <el-table-column prop="imagename" :label="'图片名'" min-width="120" fixed="left" />
                        <el-table-column prop="imagepath" :label="'图片路径'" min-width="300" />
                        <el-table-column header-align="center" align="center" :label="'图片预览'" min-width="200">
                            <template slot-scope="scope">
                                <div class="imgBox" @click="handlePictureCardPreview(scope.row.imagepath)">
                                    <img class="img" :src="`${imgBaseURL}/images/${botData.id}/${scope.row.imagepath}`">
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="180">
                            <template slot-scope="scope">
                                <!-- <el-button type="success" size="mini" @click="editHandle(scope.row)">{{ $t('button.edit') }}</el-button> -->
                                <el-button type="danger" size="mini" @click="deleteHandle(scope.row)">{{ $t('button.delete') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination
                        :current-page="pages.page"
                        :page-sizes="[1, 5, 10, 15]"
                        :page-size="pages.size"
                        layout="prev, pager, next, total, sizes, jumper"
                        :total="pages.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </el-row>
            </el-card>
        </div>
        <!-- 图片预览弹出层 -->
        <el-dialog :visible.sync="dialogPreviewVisible" width="60%" @close="dialogPreviewVisibleClose">
            <img width="100%" :src="dialogImageUrl">
        </el-dialog>
        <!-- 添加\删除弹出层 -->
        <el-dialog title="添加项目图片" :visible.sync="dialogAddVisible" width="30%" @close="dialogAddVisibleClose">
            <el-form ref="dialogFrom" :model="dialogFrom" label-width="80px" class="dialog-from">
                <el-form-item label="图片名称">
                    <el-input v-model="dialogFrom.imgMsg" placeholder="请输入图片名称" />
                </el-form-item>
                <el-form-item label="图片类型">
                    <el-select v-model="dialogFrom.imgType" placeholder="请选择项目类型" clearable>
                        <el-option v-for="(item, index) in imgTypeData" :key="index" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上传图片">
                    <el-upload
                        ref="upload"
                        action="#"
                        list-type="picture-card"
                        :limit="1"
                        :file-list="fileList"
                        :class="{ disabled: fileComputed }"
                        :on-change="handleUpload"
                        :http-request="requestImg"
                        :before-upload="befroeUpload"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                    >
                        <i class="el-icon-plus" />
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendAdditem">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import $ from 'jquery'
import { getData } from '@/utils/auth'
import { getImageList, deleteItmeImg, addBuildImg } from '@/api/BotRequest'
import { UploadImg, deteleImg } from '@/api/Upload'
import { mapGetters } from 'vuex'

export default {
    components: {},
    data() {
        return {
            botData: {},
            tableHeight: null,
            searchForm: { appname: '' },
            loading: false,
            tableData: [],
            pages: {
                page: 1,
                size: 10,
                total: 0
            },
            dialogPreviewVisible: false,
            dialogImageUrl: '',
            dialogAddVisible: false,
            dialogFrom: { imgMsg: '', imgType: '' },
            imgTypeData: [
                { value: 0, label: '平面图' },
                { value: 1, label: '结构图' },
                { value: 2, label: '其他' }
            ],
            fileList: [],
            thatFileNmae: '',
            sendState: false
        }
    },
    // 监听属性 类似于data概念
    computed: {
        ...mapGetters(['imgBaseURL']),
        fileComputed() {
            return this.fileList.length === 1
        }
    },
    // 监控data中的数据变化
    watch: {},
    created() {}, // 生命周期 - 创建完成（可以访问当前this实例）
    mounted() {
        this.botData = getData('BotData')
        this.getImagesLsit()
        this.setTableHeight()
        window.onresize = () => {
            this.setTableHeight()
        }
    }, // 生命周期 - 挂载完成（可以访问DOM元素）
    beforeCreate() {}, // 生命周期 - 创建之前
    beforeMount() {}, // 生命周期 - 挂载之前
    beforeUpdate() {}, // 生命周期 - 更新之前
    updated() {}, // 生命周期 - 更新之后
    beforeDestroy() {}, // 生命周期 - 销毁之前
    destroyed() {}, // 生命周期 - 销毁完成
    activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
    // 方法集合
    methods: {
        // 动态设置表格高
        setTableHeight() {
            var num = $(window).height() - 297
            this.tableHeight = num
        },

        // 获取图片列表
        async getImagesLsit() {
            this.loading = true
            const obj = {
                imagemanager: {
                    appid: this.botData.id,
                    imagename: this.searchForm.appname
                },
                pages: {
                    page: this.pages.page,
                    size: this.pages.size
                }
            }
            try {
                const {
                    data: { records, current, size, total }
                } = await getImageList(obj)
                this.tableData = records
                this.pages.page = current
                this.pages.size = size
                this.pages.total = total
            } catch (error) {
                console.log(error)
            } finally {
                this.loading = false
            }
        },

        // 添加项目图片按钮
        addItem() {
            this.dialogAddVisible = true
            this.sendState = false
        },
        // 确定按钮发送添加请求
        async sendAdditem() {
            const obj = {
                appid: this.botData.id,
                imagepath: this.thatFileNmae,
                imagename: this.dialogFrom.imgMsg,
                imagetype: this.dialogFrom.imgType
            }
            try {
                const { message } = await addBuildImg(obj)
                this.$message.success(message)
                this.sendState = true
            } catch (error) {
                console.log(error)
            } finally {
                this.dialogAddVisible = false
                this.getImagesLsit()
            }
        },

        /* 新增项目图片钩子函数 */
        // 选择图片事件(文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用)
        handleUpload(file, fileList) {
            if (!this.fileList.some(item => item.uid === file.uid)) {
                this.fileList.push(file)
            }
        },
        // 上传校验
        befroeUpload(file) {
            const fileType = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
            if (!fileType.some(item => item === file.type)) {
                this.$message.error('上传文件格式不正确')
                return false
            }
            const maxSize = 5 * 1024 * 1024
            if (file.size > maxSize) {
                this.$message.error('上传文件过大')
                return false
            }
            return true
        },
        // 上传
        async requestImg(params) {
            if (params.file) {
                const formData = new FormData()
                formData.append('file', params.file)
                const { data } = await UploadImg(this.botData.id, formData)
                this.thatFileNmae = data
            }
        },
        // 图片预览
        handlePreview(file) {
            console.log(file.url)
            this.dialogPreviewVisible = true
            this.dialogImageUrl = file.url
        },
        // 删除当前图片
        async handleRemove(file, fileList) {
            this.fileList = this.fileList.filter(item => {
                item.uid === file.uid
            })
            console.log(this.thatFileNmae, this.botData.id)
            const res = await deteleImg(this.thatFileNmae, this.botData.id)
            console.log(res)
        },

        // 批量删除项目图片
        batchRemove() {},

        /* table-itme项修改 */
        // 图片预览
        handlePictureCardPreview(file) {
            this.dialogPreviewVisible = true
            this.dialogImageUrl = `${this.imgBaseURL}/images/${this.botData.id}/${file}`
        },
        // 编辑
        editHandle() {
            this.dialogAddVisible = true
        },
        // 删除
        async deleteHandle(data) {
            this.$confirm('此操作将永久删除当前数据, 是否继续?', '确认操作', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async() => {
                    const { message } = await deleteItmeImg(data.imageid)
                    if (this.tableData.length === 1) {
                        if (this.pages.page > 1) {
                            this.pages.page--
                        } else {
                            this.pages.page = 1
                        }
                    }
                    await this.getImagesLsit()
                    this.$message.success({ message })
                })
                .catch(async error => {
                    console.log(error)
                    await this.getImagesLsit()
                })
        },

        /* 预览弹出框关闭事件 */
        dialogPreviewVisibleClose() {
            this.dialogImageUrl = ''
        },
        async dialogAddVisibleClose() {
            if (!this.sendState && this.fileList.length > 0) {
                await deteleImg(this.thatFileNmae, this.botData.id)
            }
            this.dialogFrom = { imgMsg: '', imgType: '' }
            this.fileList = []
            this.thatFileNmae = ''
        },

        // 分页当前页切换
        handleCurrentChange(newPage) {
            this.pages.page = newPage
            this.getImagesLsit()
        },
        // 分页显示条数切换
        handleSizeChange(newSize) {
            this.pages.size = newSize
            this.getImagesLsit()
        }
    }
}
</script>

<style scoped>
.el-table {
    margin-top: 10px;
}
.el-pagination {
    margin-top: 10px;
}
.el-form {
    margin-left: 0;
}
</style>

<style lang="scss" scoped>
.row1 {
    margin-bottom: 10px;
    .search {
        border: 1px solid #dcdfe6;
        border-top: none;
        padding: 34px 10px 10px 10px;
        margin-top: -14px;
        .el-input {
            width: 300px;
        }
    }
}
.imgBox {
    display: inline-block;
    max-width: 100px;
    cursor: pointer;
    img {
        width: 100%;
        height: 100%;
    }
}
.dialog-from {
    .el-input {
        width: calc(100% - 30px);
    }
    .el-upload {
        margin-top: 15px;
    }
    ::v-deep .disabled {
        .el-upload--picture-card {
            display: none;
        }
    }
}
</style>
